package com.guqj.nio.netty.pstack.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.guqj.nio.netty.pstack.util.NettyConstant;
import com.guqj.nio.netty.pstack.util.NettyMessageDecoder;
import com.guqj.nio.netty.pstack.util.NettyMessageEncoder;

public class NettyClient {

	private EventLoopGroup group = new NioEventLoopGroup();
	private ExecutorService executor = Executors.newSingleThreadScheduledExecutor();

	public void connect(int port, String ip) throws InterruptedException {
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4, -8, 0))
									.addLast("MessageEncoder", new NettyMessageEncoder())
									.addLast("ReadTimeoutHandler", new ReadTimeoutHandler(5))
									.addLast("LoginAuthHandler", new LoginAuthReqHandler())
									.addLast("HeartBeatHandler", new HeartBeatReqHandler());
						}
					});
			ChannelFuture c = b.connect(ip, port).sync();
			System.out.println("Netty client connect server ok : " + ip + ":" + port);
			c.channel().closeFuture().sync();
		} finally {
			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						TimeUnit.SECONDS.sleep(5);
						connect(NettyConstant.PORT, NettyConstant.REMOTE_IP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new NettyClient().connect(NettyConstant.PORT, NettyConstant.REMOTE_IP);
	}
}
